﻿using Leeder.Bluetooth;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Bluetooth.SmartBracelet2
{
    public partial class SmartBraceletUserControl : UserControl
    {
        protected int status = 0;
        protected IBLEHandler bLEHandler = null;
        protected string mac = null;
        protected string worker = null;
        public event Action<string, string, string> SendDataEvent;
        public event Action<object> ChangedEvent;
        public int Status => status;
        public string SelectedSmartBracelet => cmbSmartBracelet.Text;
        public string SelectedWorker => cmbWorker.Text;


        public SmartBraceletUserControl()
        {
            InitializeComponent();
        }

        public void SetSmartBraceletItemList(List<SmartBraceletItem> items)
        {
            this.Invoke(new Action(() =>
            {
                cmbSmartBracelet.Items.Clear();
                cmbSmartBracelet.DisplayMember = "Text";
                cmbSmartBracelet.ValueMember = "Value";
                cmbSmartBracelet.Items.Add(new { Text = "", Value = "" });
                if (items != null && items.Count > 0)
                {
                    foreach (SmartBraceletItem item in items)
                    {
                        cmbSmartBracelet.Items.Add(new { Text = item.Name, Value = item.Mac });
                    }
                }
            }));
        }

        public void SelectSmartBracelet(string str)
        {
            this.Invoke(new Action(() =>
            {
                foreach (var item in cmbSmartBracelet.Items)
                {
                    var anonymousItem = item as dynamic;
                    if (anonymousItem != null && anonymousItem.Text == str)
                    {
                        cmbSmartBracelet.SelectedItem = item;
                        break;
                    }
                }
            }));
        }

        public void SelectWorker(string str)
        {
            this.Invoke(new Action(() =>
            {
                cmbWorker.Text = str;
                worker = str;
            }));
        }

        public void Connect()
        {
            try
            {
                if (!string.IsNullOrWhiteSpace(cmbSmartBracelet.Text))
                {
                    mac = (cmbSmartBracelet.SelectedItem as dynamic)?.Value;
                    DisConnect();
                    if (IsMacAddress(mac))
                    {
                        bLEHandler = new BLEHandler(mac);
                        bLEHandler.OnConnectionChanged += Handler_OnConnectionChanged;
                        bLEHandler.OnReceive += Handler_OnReceive;
                        bLEHandler.OnErrorMessage += Handler_OnErrorMessage;
                        bLEHandler.Start();
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        private void Handler_OnErrorMessage(string arg1, Exception arg2)
        {
            Debug.WriteLine($"异常信息：【{arg1}】{arg2.Message}");
        }

        private void Handler_OnConnectionChanged(bool obj)
        {
            var result = obj ? "连接成功" : "连接断开";
            Debug.WriteLine($"连接状态变化：【{result}】");
            status = obj ? 1 : 0;
            this.Invoke(new Action(()=>
            {
                lblStatus.Visible = obj;
                cmbSmartBracelet.Enabled = !obj;
                btnConnect.Text = obj ? "断开" : "连接";
            }));
        }

        private void Handler_OnReceive(byte[] obj)
        {
            string str = Encoding.UTF8.GetString(obj);
            Debug.WriteLine($"接收到消息：{str}");
            SendDataEvent?.Invoke(worker, bLEHandler.GetDeviceMac(), str);
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (status == 0)
            {
                Connect();
            }
            else
            {
                DisConnect();
                //this.Invoke(new Action(() =>
                //{
                //    lblStatus.Visible = false;
                //    cmbSmartBracelet.Enabled = true;
                //    btnConnect.Text = "连接";
                //}));
            }
        }
        public void DisConnect()
        {
            try
            {
                bLEHandler?.Stop();
            }
            catch
            { }
        }

        protected bool IsMacAddress(string input)
        {
            string pattern = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$";
            Regex regex = new Regex(pattern);
            return regex.IsMatch(input);
        }

        private void cmbSmartBracelet_SelectedIndexChanged(object sender, EventArgs e)
        {
            ChangedEvent?.Invoke(this);
        }

        private void cmbWorker_SelectedIndexChanged(object sender, EventArgs e)
        {
            worker = cmbWorker.Text;
        }
    }
}
